﻿import serial
import math
import os
import serial.tools.list_ports
# from collections import Counter
import random
import matplotlib.pyplot as plt
import numpy as np

plist = list(serial.tools.list_ports.comports())

# frontPort = 'com10'
# backPort = 'com3'
filename = "data" + str(random.uniform(0,1))

keyData = []
keyDataIndexArr = []
keyDataIndex = 0

def getData(serPort):
    data = []
    peak = []
    ser = serial.Serial(serPort,115200,timeout=0.5)
    lock = False
    while(True):
        s = str(ser.readline())
        # print(s)
        if s == "b\'Envelope data:\\n\'":
            while(True):
                s = str(ser.readline())
                s = s.replace("b\'", "")
                s = s.replace("\\n\'", "")
                if s == "end":
                    lock = True
                    break
                temp = s.split()
                data.extend(temp)
        if lock:
            dataLen = len(data)
            for p in data:
	            p = int(p)
	            peak.append(p)
            distance = [i for i in range(dataLen)]
            distance = np.array(distance) * 0.484
            getKeyData(peak, keyData, keyDataIndex, keyDataIndexArr)
            ser.close()
            return distance, peak

def plotData(xData, yData, title, xlabel, ylabel, subplotPos):
    plt.subplot(subplotPos)
    plt.title(title)
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    plt.plot(xData, yData)

def getKeyData(peak, keyData, keyDataIndex, keyDataIndexArr):
    #输出最值并用文档记录
    keyDistance = peak.index(max(peak)) * 0.484
    print(keyDistance)
    dataString = str(max(peak)) + '\t' + str(keyDistance) + '\t'

    with open(filename,"a") as f:
        f.write(dataString)

    if keyDataIndex > 10:
        keyData.pop(0)
        keyData.append(keyDistance)
        keyDataIndexArr.pop(0)
        keyDataIndexArr.append(keyDataIndex)
    else:
        keyData.append(keyDistance)
        keyDataIndexArr.append(keyDataIndex)

def plotResult():
    plt.clf()
    plotData(distance, peak, 'envelope', 'Distance(mm)', 'Peak', 211)
    plotData(keyDataIndexArr, keyData, 'maxPeakDistance', 'testIndex(n)', 'Distance', 212)
    plt.draw()
    plt.pause(0.1)
    plt.ioff()

while True:
    keyDataIndex = keyDataIndex + 1
    distance, peak = getData('com6')
    plt.ion()
    plotResult()
    plt.ioff()